package ServletDemo01;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		FileItemFactory factory = new DiskFileItemFactory();

		// 文件上传处理器
		ServletFileUpload upload = new ServletFileUpload(factory);

		// 解析请求信息
		List items = null;
		try {
			items = upload.parseRequest(request);
		}
		catch (FileUploadException e) {
			e.printStackTrace();
		}

		// 对请求信息进行判断
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			// 信息为普通的格式
			if (item.isFormField()) {
				String fieldName = item.getFieldName();
				String value = item.getString();
				request.setAttribute(fieldName, value);
			}
			// 信息为文件格式
			else {
				String fileName = item.getName();//获得上传图片的名称
				int index = fileName.lastIndexOf("\\");
				fileName = fileName.substring(index + 1);
				//避免同名文件覆盖
				fileName= UUID.randomUUID().toString()+fileName;
				request.setAttribute("realFileName", fileName);
//                 不建议保存到项目里面
//                 String basePath =  request.getSession().getServletContext().getRealPath("/images");
//                自定义文件存放目录（文件服务器）
				String basePath="D:\\study\\web\\javaweb\\MavenProject02\\files";
				System.out.println(basePath);//打印当前位置
				File fileDir = new File(basePath);
				//创建文件夹
				if(!fileDir.exists()) {
					fileDir.mkdirs();
				}
				File file = new File(basePath, fileName);

				try {

					item.write(file);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
